﻿using System;
using System.Collections.Generic;
using System.Windows;
using System.Windows.Media;
using System.Threading;
using System.Windows.Threading;
using PersonalHealth.Data.Model;
using HealthManagement.Common;
using PersonalHealth.Data.IService;
using PersonalHealth.Data.Service;
using com.jwxcd.CommunityDriver;
using System.Windows.Controls;

namespace HealthManagement.Views
{
    /// <summary>
    /// BloodPressure.xaml 的交互逻辑
    /// </summary>
    public partial class BloodPressure : MeasureBase
    {
        MeasureUser user;
        IList<Threshold> thresholds;
        UserPanel parentPage;
        public BloodPressure(MeasureUser user, UserPanel p)
        {
            InitializeComponent();
            this.user = user;
            this.parentPage = p;
            this.Loaded += new RoutedEventHandler(BloodPressure_Loaded);
        }

        void BloodPressure_Loaded(object sender, RoutedEventArgs e)
        {
            testStepGrid.Visibility = Visibility.Visible;

            Dispatcher.BeginInvoke(
                new Action(
                  () =>
                  {
                      connectTimer = new DispatcherTimer();
                      connectTimer.Interval = new TimeSpan(10000000);
                      connectTimer.Tick += new EventHandler(connectTimer_Tick);
                      connectSecondsCount = 0;
                      connectTimer.Start();
                  }
                )
            );
            driver.connect();
        }


        DispatcherTimer connectTimer;
        int connectSecondsCount = 0;
        void connectTimer_Tick(object sender, EventArgs e)
        {
            connectSecondsCount++;
            connectDown.Text = (30 - connectSecondsCount).ToString();
            if (connectSecondsCount == 30)
            {
                DispatcherTimer timer = sender as DispatcherTimer;
                timer.Stop();

                OnError("连接设备超时，请返回重试！");
            }
        }

        DateTime connectTime;
        public override void onDriverConnected(object sender, EventArgs e)
        {
            Thread.Sleep(500);
            Action variable = () =>
            {
                if (connectTimer != null)
                    connectTimer.Stop();
                testStepStack.Visibility = Visibility.Collapsed;
                testStepStack1.Visibility = Visibility.Visible;

                IUserService service = new UserService();
                thresholds = service.GetThreshold("BP", user.Id);

                Thread.Sleep(200);
                driver.SetDeviceState(MeterType.StartBP);
                connectTime = DateTime.Now;
            };
            Dispatcher.Invoke(new Action(
                variable));

        }

        bool flag = false;
        public override void onMeasure(object sender, MeasureEventArgs e)
        {
            if (driver.IsMeterTypeEnd && (DateTime.Now - connectTime).TotalSeconds > 2
                && !flag && e.value.SBP != 0 && e.value.DBP != 0 && e.value.PressurePulse != 0)
            {
                flag = true;
                driver.SetDeviceState(MeterType.EndBP);
                Dispatcher.Invoke(new Action(
               () =>
               {
                   if (resultStepGrid.Visibility == Visibility.Collapsed)
                   {
                       testStepGrid.Visibility = Visibility.Collapsed;
                       resultStepGrid.Visibility = Visibility.Visible;
                   }
                   //收缩压
                   SBP.Text = e.value.SBP.ToString();
                   //舒张压
                   DBP.Text = e.value.DBP.ToString();
                   //脉率
                   HR_value.Text = e.value.PressurePulse.ToString();

                   foreach (var i in thresholds)
                   {
                       if (i.MeasureSubType.Code == "SBP")
                       {
                           if (e.value.SBP < i.Min || e.value.SBP > i.Max)
                           {
                               sbpPanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ff8700")) as Brush;
                           }
                           else
                           {
                               sbpPanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF6D9700")) as Brush;
                           }
                       }
                       if (i.MeasureSubType.Code == "DBP")
                       {
                           if (e.value.DBP < i.Min || e.value.DBP > i.Max)
                           {
                               dbpPanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ff8700")) as Brush;
                           }
                           else
                           {
                               dbpPanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF6D9700")) as Brush;
                           }
                       }
                       if (i.MeasureSubType.Code == "HR_Value")
                       {
                           if (e.value.PressurePulse < i.Min || e.value.PressurePulse > i.Max)
                           {
                               pulsePanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#ff8700")) as Brush;
                           }
                           else
                           {
                               pulsePanel.Background = new SolidColorBrush((Color)ColorConverter.ConvertFromString("#FF6D9700")) as Brush;
                           }
                       }
                   }

                   Save.Visibility = Visibility.Visible;
                   Cancel.Visibility = Visibility.Visible;

                   saveTimer = new DispatcherTimer();
                   saveTimer.Interval = new TimeSpan(10000000);
                   saveTimer.Tick += new EventHandler(saveTimer_Tick);
                   saveSecondsCount = 0;
                   saveTimer.Start();

                   countDownInfo.Visibility = Visibility.Visible;
               }
                ));
            }
        }

        DispatcherTimer saveTimer;
        int saveSecondsCount = 0;
        void saveTimer_Tick(object sender, EventArgs e)
        {
            saveSecondsCount++;
            seconds.Text = (10 - saveSecondsCount).ToString();
            if (saveSecondsCount == 10)
            {
                DispatcherTimer timer = sender as DispatcherTimer;
                timer.Stop();
                Save.IsEnabled = false;
                Cancel.IsEnabled = false;
                save();
                Save.IsEnabled = true;
                Cancel.IsEnabled = true;
                parentPage.btnStop.IsEnabled = false;
                parentPage.contentBorder.Content = null;
                OnNotice("测试数据已自动保存！");
            }
        }


        private void Save_Click(object sender, RoutedEventArgs e)
        {
            if (saveTimer != null)
                saveTimer.Stop();
            save();
            //NavigationService.Refresh();
            parentPage.btnStop.IsEnabled = false;
            parentPage.contentBorder.Content = null;
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            if (saveTimer != null)
                saveTimer.Stop();
            //NavigationService.GoBack();
            parentPage.btnStop.IsEnabled = false;
            parentPage.contentBorder.Content = null;

        }

        private object lockObj = new object();
        private bool isUnload = false;
        public override void MeasureBase_Unloaded(object sender, RoutedEventArgs e)
        {
            lock (lockObj)
            {
                if (isUnload)
                {
                    return;
                }
                else
                {
                    if (saveTimer != null)
                        saveTimer.Stop();
                    if (connectTimer != null)
                        connectTimer.Stop();

                    driver.SetDeviceState(MeterType.EndBP);
                    while (!driver.IsMeterTypeEnd)
                        ;//no code
                    base.MeasureBase_Unloaded(sender, e);
                    isUnload = true;

                }
            }

        
        }

        private void save()
        {
            int sbp, dbp, pressurePulse;
            int.TryParse(SBP.Text, out sbp);
            int.TryParse(DBP.Text, out dbp);
            int.TryParse(HR_value.Text, out pressurePulse);
            Measure_BP obj = new Measure_BP();
            obj.UserId = user.Id;
            obj.SBP = sbp;
            obj.DBP = dbp;
            obj.HR_Value = pressurePulse;
            DateTime now = DateTime.Now;
            obj.MeasureTime = obj.CreateDate = obj.ModifyDate = now;

            IMeasure_BPService ser = new Measure_BPService();
            ser.Add(obj);
        }
       
    }
}
